<?php
/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2017/12/20
 * Time: 上午9:38
 */

defined('BASEPATH') OR exit('No direct script access allowed');

function send_msg($tel, $msg, $code, $apikey)
{
    // 发送短信
    $error_msg = '对不起，短信发送失败，请联系服务商';
    $res = false;
    try {
        $res = send_message($tel, $msg, $apikey);
    } catch (\Exception $e) {
        $error_msg = $e->getMessage();
    }

    if ($res) {
        $data1['time'] = date("Y-m-d H:i:s");
        $data1['code'] = $code;
        $_SESSION[$tel . "code"] = json_encode($data1);
        return array('status' => 1, 'msg' => 'success');
    }
    return array('status' => 0, 'msg' => $error_msg);
}

// 发送短信使用
function send_message($tel, $msg, $apikey)
{
    header("Content-Type:text/html;charset=utf-8");
    $mobile = $tel;
    $text = $msg;
    $ch = curl_init();

    /* 设置验证方式 */
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8',
        'Content-Type:application/x-www-form-urlencoded', 'charset=utf-8'));
    /* 设置返回结果为流 */
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    /* 设置超时时间*/
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    /* 设置通信方式 */
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// 取得用户信息
//    $json_data = get_user($ch,$apikey);
//    if(json_decode($json_data,true)['code'] != 0)
//    {
//        log_message('error','短信发送失败,设置错误：'.$json_data);
//    }

// 发送短信
    $data = array('text' => $text, 'apikey' => $apikey, 'mobile' => $mobile);
    $json_data = send($ch, $data);
    $array = json_decode($json_data, true);
    if ($array['code'] == 0) {
        return true;
    } else {
        log_message('error', '短信发送失败：' . json_encode($array));
        throw new Exception($array['msg']);
    }


}

//获得账户
function get_user($ch, $apikey)
{
    curl_setopt($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/user/get.json');
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('apikey' => $apikey)));
    $result = curl_exec($ch);
    $error = curl_error($ch);
    checkErr($result, $error);
    return $result;
}

function send($ch, $data)
{
    curl_setopt($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/sms/single_send.json');
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    $result = curl_exec($ch);
    $error = curl_error($ch);
    checkErr($result, $error);
    return $result;
}

function checkErr($result, $error)
{
    if ($result === false) {
        log_message('error', '短信发送错误：' . $error);
    } else {
        //echo '操作完成没有任何错误';
    }
}

function check_uniqueness($db, $db_name, $column, $data)
{
    $res = $db->query("select count(1) as res from $db_name WHERE $column = '$data' ")->row_array();
    if ($res && $res['res']) {
        return false;
    }
    return true;
}


//生成随机验证码
function generate_code($length = 6)
{
    return rand(pow(10, ($length - 1)), pow(10, $length) - 1);
}

// 验证手机号码
function is_mobile($str)
{
    return preg_match("/^1[34578]{1}\d{9}$/", $str);
}

// 校验入参
function check_param($fl, $params)
{
    if (!$params || !is_array($params)) {
        return false;
    }
    foreach ($params as $p) {
        if (!isset($fl[$p]) || (!$fl[$p] && $fl[$p] != 0)) {
            return false;
        }
    }
    return true;
}

/**
 * 判断是否为合法的身份证号码
 * @param $mobile
 * @return int
 */
function isCreditNo($vStr)
{
    $vCity = array(
        '11', '12', '13', '14', '15', '21', '22',
        '23', '31', '32', '33', '34', '35', '36',
        '37', '41', '42', '43', '44', '45', '46',
        '50', '51', '52', '53', '54', '61', '62',
        '63', '64', '65', '71', '81', '82', '91'
    );
    if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
    if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
    $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
    $vLength = strlen($vStr);
    if ($vLength == 18) {
        $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
    } else {
        $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
    }
    if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
    if ($vLength == 18) {
        $vSum = 0;
        for ($i = 17; $i >= 0; $i--) {
            $vSubStr = substr($vStr, 17 - $i, 1);
            $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
        }
        if ($vSum % 11 != 1) return false;
    }
    return true;
}

// 生成订单
function trade_no()
{
    list($usec, $sec) = explode(" ", microtime());
    $usec = substr(str_replace('0.', '', $usec), 0, 4);
    $str = rand(10, 99);
    return date("YmdHis") . $usec . $str;
}

/**
 * 计算两个坐标之间的距离(米)
 * @param float $fP1Lat 起点(纬度)
 * @param float $fP1Lon 起点(经度)
 * @param float $fP2Lat 终点(纬度)
 * @param float $fP2Lon 终点(经度)
 * @return int
 */
function distanceBetween($fP1Lat, $fP1Lon, $fP2Lat, $fP2Lon)
{
    $fEARTH_RADIUS = 6378137;
    //角度换算成弧度
    $fRadLon1 = deg2rad($fP1Lon);
    $fRadLon2 = deg2rad($fP2Lon);
    $fRadLat1 = deg2rad($fP1Lat);
    $fRadLat2 = deg2rad($fP2Lat);
    //计算经纬度的差值
    $fD1 = abs($fRadLat1 - $fRadLat2);
    $fD2 = abs($fRadLon1 - $fRadLon2);
    //距离计算
    $fP = pow(sin($fD1 / 2), 2) +
        cos($fRadLat1) * cos($fRadLat2) * pow(sin($fD2 / 2), 2);
    return intval($fEARTH_RADIUS * 2 * asin(sqrt($fP)) + 0.5);
}

/**
 * 接口请求
 */
//参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
function curl_request($url, $post = '', $cookie = '', $returnCookie = 0)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
    if ($post) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    if ($cookie) {
        curl_setopt($curl, CURLOPT_COOKIE, $cookie);
    }
    curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return curl_error($curl);
    }
    curl_close($curl);
    if ($returnCookie) {
        list($header, $body) = explode("\r\n\r\n", $data, 2);
        preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
        $info['cookie'] = substr($matches[1][0], 1);
        $info['content'] = $body;
        return $info;
    } else {
        return $data;
    }
}

// 两个日期相差天数
function diffBetweenTwoDays($day1, $day2)
{
    $second1 = strtotime($day1);
    $second2 = strtotime($day2);

    if ($second1 < $second2) {
        $tmp = $second2;
        $second2 = $second1;
        $second1 = $tmp;
    }
    return ceil(($second1 - $second2) / 86400);
}

function encrypt($id)
{
    $id = serialize($id);
    $key = "11111111222111122221111";
    $data['iv'] = base64_encode(substr('fdakinel;injajdji', 0, 16));
    $data['value'] = openssl_encrypt($id, 'AES-256-CBC', $key, 0, base64_decode($data['iv']));
    $encrypt = base64_encode(json_encode($data));
    return $encrypt;
}

function array_group_by($arr, $key)
{
    $grouped = [];
    foreach ($arr as $value) {
        $grouped[$value[$key]][] = $value;
    }
    if (func_num_args() > 2) {
        $args = func_get_args();
        foreach ($grouped as $key => $value) {
            array_group_by([$value], array_slice($args, 2, func_num_args()));
        }
    }
    return $grouped;
}

function decrypt($encrypt)
{
    $key = '11111111222111122221111';//解密钥匙
    $encrypt = json_decode(base64_decode($encrypt), true);
    $iv = base64_decode($encrypt['iv']);
    $decrypt = openssl_decrypt($encrypt['value'], 'AES-256-CBC', $key, 0, $iv);
    $id = unserialize($decrypt);
    if ($id) {
        return $id;
    } else {
        return 0;
    }
}

function get_nonce_number($length = 11)
{
    $chars = "0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

function get_order_id($length = 16)
{
    //见方法一，获得毫秒级别时间戳
    $time = self::get_millisecond();
    $len = $length - 13;
    $str = self::get_nonce_number($len);
    if (strlen($time) != 13) {
        $orderId = $str . $time . rand(1, 9);
    } else {
        $orderId = $str . $time;
    }
    return $orderId;

}

// 防sql注入,xss攻击
function clean($str)
{
    $str = trim($str);
    $str = strip_tags($str);
    $str = stripslashes($str);
    $str = addslashes($str);
    $str = rawurldecode($str);
    $str = quotemeta($str);
    $str = htmlspecialchars($str);
    return $str;
}

// 生成api token
function create_token($post, $token_const)
{
    foreach ($post as $k => $p) {
        if ($p != '' && $k != 'token' && $k != 'callback') {
            $arr[$k] = $p;
        }
    }
    // 按首字母大小写顺序排序
    sort($arr, SORT_STRING);
    // 拼接成字符串
    $str = implode($arr);
    $str = $str . $token_const;
    // 进行加密
    $signature = sha1($str);
    $signature = md5($signature);
    // 转换成大写
    $signature = strtoupper($signature);
    return $signature;

}

// 验签
function check_token($token, $p_token, $p_time, $time_out)
{
    if ($token != $p_token) {
        return ['status' => -1, 'msg' => '验签失败'];
    }
    $xx = time();
    $x_time = time() - $p_time;
    if ($time_out < $x_time) {
        return ['status' => -1, 'msg' => '超时'];
    }
    return ['status' => 0, 'msg' => 'success'];
}

function wait_time($time)
{
    $time = strtotime($time);
    $timediff = time() - $time;
    $days = intval($timediff / 86400);
//计算小时数
    $remain = $timediff % 86400;
    $hours = intval($remain / 3600);
//计算分钟数
    $remain = $remain % 3600;
    $mins = intval($remain / 60);
//计算秒数
    $secs = $remain % 60;
    return $days . '天' . $hours . '小时' . $mins . '分' . $secs . '秒';
}


function modify_url($mod)
{
    $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $query = explode("&", $_SERVER['QUERY_STRING']);
    if (!$_SERVER['QUERY_STRING']) {
        $queryStart = "?";
    } else {
        $queryStart = "&";
    }
    // modify/delete data

    foreach ($query as $q) {
        if ($q) {
            list($key, $value) = explode("=", $q);
            if (array_key_exists($key, $mod)) {
                if ($mod[$key]) {
                    $url = preg_replace('/' . $key . '=' . $value . '/', $key . '=' . $mod[$key], $url);
                } else {
                    $url = preg_replace('/&?' . $key . '=' . $value . '/', '', $url);
                }
            }
        }
    }
    $i = 0;
    // add new data
    foreach ($mod as $key => $value) {
        if ($value && !preg_match('/' . $key . '=/', $url)) {
            if ($i == 1) {
                $queryStart = "&";
            }
            $url .= $queryStart . $key . '=' . $value;
            $i++;
        }
    }
    return $url;
}